import { api, getCurrentUser } from './api.js';

document.addEventListener('DOMContentLoaded', async () => {
    // 检查登录状态
    const user = await getCurrentUser();
    if (!user) {
        window.location.href = 'index.html';
        return;
    }

    // 加载订单数据
    loadOrders();

    // 退出登录
    document.getElementById('logout-btn').addEventListener('click', async (e) => {
        e.preventDefault();
        try {
            await api.post('/auth/logout');
            window.location.href = 'index.html';
        } catch (error) {
            console.error('退出登录失败:', error);
        }
    });
});

async function loadOrders() {
    const loading = document.getElementById('loading');
    const ordersContainer = document.getElementById('orders-container');
    
    try {
        // 获取订单历史
        const orders = await api.get('/orders/history');
        loading.style.display = 'none';

        if (orders.length === 0) {
            ordersContainer.innerHTML = `
                <div class="no-orders">
                    <p>您还没有任何订单</p>
                    <a href="order.html" class="btn">去下单</a>
                </div>
            `;
            return;
        }

        // 渲染订单列表
        ordersContainer.innerHTML = orders.map(order => createOrderCard(order)).join('');
    } catch (error) {
        loading.style.display = 'none';
        ordersContainer.innerHTML = `
            <div class="error-message">
                <p>加载订单失败: ${error.message}</p>
                <button onclick="location.reload()" class="btn">重试</button>
            </div>
        `;
    }
}

function createOrderCard(order) {
    // 格式化日期
    const orderDate = new Date(order.created_at).toLocaleString();
    
    // 根据状态设置样式
    let statusClass = '';
    switch (order.status.toLowerCase()) {
        case 'pending':
            statusClass = 'status-pending';
            break;
        case 'completed':
            statusClass = 'status-completed';
            break;
        case 'cancelled':
            statusClass = 'status-cancelled';
            break;
        default:
            statusClass = 'status-pending';
    }

    // 生成订单项HTML
    const itemsHtml = order.items.map(item => `
        <div class="order-item">
            <div class="item-name">${item.name}</div>
            <div class="item-quantity">× ${item.quantity}</div>
            <div class="item-price">¥ ${item.price.toFixed(2)}</div>
        </div>
    `).join('');

    return `
        <div class="order-card">
            <div class="order-header">
                <span class="order-id">订单 #${order.id}</span>
                <span class="order-status ${statusClass}">${order.status}</span>
            </div>
            <div class="order-details">
                <span class="order-amount">总价: ¥ ${order.total_amount.toFixed(2)}</span>
                <span class="order-date">${orderDate}</span>
            </div>
            <div class="order-items">
                ${itemsHtml}
            </div>
            <div class="order-actions">
                <button class="btn btn-cancel" data-order-id="${order.id}">取消订单</button>
            </div>
        </div>
    `;
}

// 取消订单功能
document.addEventListener('click', async (e) => {
    if (e.target.classList.contains('btn-cancel')) {
        const orderId = e.target.getAttribute('data-order-id');
        if (confirm('确定要取消此订单吗？')) {
            try {
                // 这里假设您有取消订单的API端点
                await api.put(`/orders/${orderId}/cancel`);
                alert('订单已取消');
                loadOrders(); // 刷新订单列表
            } catch (error) {
                alert(`取消订单失败: ${error.message}`);
            }
        }
    }
});